package BFS解决FloodFill算法;

import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;

public class test3 {
    int[] dx = {0,0,1,-1};
    int[] dy = {1,-1,0,0};
    boolean[][] flag = new boolean[51][51];
    int max = 0; //用来记录最大的岛屿位置
    int n,m;
    public int maxAreaOfIsland(int[][] grid) {
        n = grid.length;
        m = grid[0].length;

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if(grid[i][j] == 1&& !flag[i][j])
                    // 判定为岛屿
                    bfs(grid,i,j);
            }
        }
        return max;
    }

    public void bfs(int[][] grid,int sr,int sc){
        Queue<int[]> queue = new LinkedList<>();
        queue.add(new int[]{sr,sc});
        flag[sr][sc] = true;
        int count = 1;

        while (!queue.isEmpty()){
            int[] arr = queue.poll();
            int a = arr[0],b=arr[1];
            for (int i = 0; i < 4; i++) {
                int x = a+dx[i];
                int y = b+dy[i];
                if(x>=0&&x<n&&y>=0&&y<m&&grid[x][y]==1&&!flag[x][y]){
                    count++;
                    queue.add(new int[]{x,y});
                    flag[x][y] = true;
                }
            }
        }
        max = Math.max(max,count);
    }
}
